import { AppDataSource } from "@/config/database";
import { Services } from "@/entities/basis/services.entity";
import { ErrorHandler } from "@/middlewares/error.middleware";
import { TokenPayload } from "@/utils/token.util";
import { Context } from "koa";

export interface IBody extends Services {
}

/** 创建服务 */
export async function createService(ctx: Context) {
    const body = ctx.request.body as IBody;
    const user: TokenPayload = ctx.state.user;

    validateParams(body.code, body.name); // 校验参数
    await checkServiceExists(body.code); // 检查服务编号是否已存在

    // 创建服务
    const service = await saveService(body, user);

    ctx.status = 200;
    ctx.body = service;
}

/** 校验参数 */
const validateParams = (code: string, name: string) => {
    if (!code) {
        throw new ErrorHandler('服务编号不能为空', 400);
    }
    if (!name) {
        throw new ErrorHandler('服务名称不能为空', 400);
    }
}

/** 检查服务编号是否已存在 */
const checkServiceExists = async (code: string) => {
    const serviceRepository = AppDataSource.getRepository(Services);

    const existingService = await serviceRepository.findOne({
        where: { code }
    });
    if (existingService) {
        throw new ErrorHandler('服务编号已存在', 409);
    }
}

/** 保存服务到数据库 */
const saveService = async (body: IBody, user: TokenPayload) => {
    
    const serviceRepository = AppDataSource.getRepository(Services);
    const service = new Services();

    // 必填字段
    service.code = body.code.trim();
    service.name = body.name.trim();
    service.status = body.status || '0'; // 
    service.createdBy = user.id;
    service.updatedBy = user.id;

    // 可选字段 - 添加数据验证
    if (body.description) {
        service.description = body.description.trim();
    }

    if (body.category) {
        service.category = body.category.trim();
    }

    if (body.duration) {
        service.duration = body.duration;
    }

    if (body.technicianLevel) {
        service.technicianLevel = body.technicianLevel;
    }

    if (body.cashPrice) {
        service.cashPrice = body.cashPrice;
    }

    if (body.cardPrice) {
        service.cardPrice = body.cardPrice;
    }

    if (body.integral) {
        service.integral = body.integral;
    }

    try {
        return await serviceRepository.save(service);
    } catch (error) {
        // 处理数据库保存错误
        if (error.code === 'ER_DUP_ENTRY') {
            throw new ErrorHandler('服务编号已存在', 409);
        }
        throw new ErrorHandler('保存服务信息失败', 500);
    }
} 